import requests
from datetime import datetime, timedelta

class OpenMeteoRadiationFetcher:
    def __init__(self, latitude, longitude):
        self.latitude = latitude
        self.longitude = longitude
        self.base_url = "https://api.open-meteo.com/v1/forecast"

    def get_hourly_radiation(self, date_str):
        params = {
            "latitude": self.latitude,
            "longitude": self.longitude,
            "start_date": date_str,
            "end_date": (datetime.strptime(date_str, "%Y-%m-%d") + timedelta(days=2)).strftime("%Y-%m-%d"),
            "timezone": "auto",
            "hourly": "shortwave_radiation"
        }
        resp = requests.get(self.base_url, params=params)
        resp.raise_for_status()
        data = resp.json()
        time_list = data["hourly"]["time"]
        radiation_list = data["hourly"]["shortwave_radiation"]

        # 当前小时（按整点截断）
        current_hour_str = datetime.now().strftime("%Y-%m-%dT%H:00")

        # 1. 当前小时开始向后24小时的辐照度 + 时间
        next_24_hours = []
        if current_hour_str in time_list:
            start_index = time_list.index(current_hour_str)
            for i in range(start_index, min(start_index + 24, len(time_list))):
                next_24_hours.append({
                    "time": time_list[i],
                    "radiation": radiation_list[i]
                })

        # 2. 指定日期全天（0-23点）的辐照度 + 时间
        next_day = []
        for i, t in enumerate(time_list):
            if t.startswith(date_str):
                next_day.append({
                    "time": t,
                    "radiation": radiation_list[i]
                })

        return {
            "next_24_hours_radiation": next_24_hours,
            "next_day_radiation": next_day
        }

# 示例用法
if __name__ == "__main__":
    fetcher = OpenMeteoRadiationFetcher(latitude=40.45672, longitude=115.97494)
    date_str = datetime.now().strftime("%Y-%m-%d")  # 今天
    result = fetcher.get_hourly_radiation(date_str)

    print("➡️ 当前小时起未来24小时的辐照度：")
    for entry in result["next_24_hours_radiation"]:
        print(f"{entry['time']}: {entry['radiation']} W/m²")

    print("\n📆 指定日全天的辐照度：")
    for entry in result["next_day_radiation"]:
        print(f"{entry['time']}: {entry['radiation']} W/m²")
